<template>
  <div>
    <basic-container>
      <!-- 头部进度条 -->
      <div class="progress">
        <el-steps :active="activeStep" simple>
          <el-step title="基本信息" icon="el-icon-edit"></el-step>
          <el-step title="图文信息" icon="el-icon-upload"></el-step>
        </el-steps>
      </div>
      <div v-show="activeStep == 0">
        <!-- 商品信息 -->
        <avue-form :option="option" v-model="formData">
          <!-- 展示分类 -->
          <template slot-scope="scope" slot="category">
            <avue-input-tree
              v-model="formData.goodsCategoryId"
              :dic="goodsCategory"
              :props="defaultProps"
              :defaultExpandAll="true"
              type="tree"
              placeholder="请选择所属分类"/>
          </template>
          <!-- 商品主图 -->
          <template slot-scope="scope" slot="thumbUrl">
            <div>
              <div v-show="formData.thumbUrl" class="thumbUrl">
                <img :src="formData.thumbUrl"/>
                <div class="hover_show">
                  <i class="el-icon-delete" @click="handlePictureRemove"></i>
                  <i class="el-icon-view" @click="handlePicturePreview"></i>
                </div>
              </div>
              <div class="select_img" @click="sel_img(1)">
                <i class="el-icon-plus"/>
              </div>
              <el-dialog :visible.sync="sleImg" title="选择图片">
                <sel-img-photogallery ref="selImg" :type="'03'" @select="onSelectImgs">
                </sel-img-photogallery>
              </el-dialog>
              <el-dialog :visible.sync="picturePreviewVisible" title="商品主图">
                <div class="picturePreviewDialog">
                  <img :src="formData.thumbUrl" style="width:100%;height:100%;">
                </div>
              </el-dialog>
            </div>
          </template>
          <!-- 商品轮播图 -->
          <template slot-scope="scope" slot="photoList">
            <div>
              <div v-for="(item,index) in formData.photoList" :key="index" class="thumbUrl">
                <img :src="item.picUrl"/>
                <div class="hover_show">
                  <i class="el-icon-delete" @click="sliderPictureRemove(index)"></i>
                </div>
              </div>
              <div class="select_img" style="float: left;" @click="sel_img(2)"><i class="el-icon-plus"></i></div>
            </div>
          </template>
        </avue-form>
        <!-- 规格表单 -->
        <div class="goods-models-wrap">
          <goods-model-selecter ref="goodsModelsComponent"
                                :has-model="true"
                                @getModelInfo="getModelInfo"
                                :goods-info="formData"
                                :type="false"
          ></goods-model-selecter>
        </div>
        <div class="button-group__center">
          <el-button type="default" @click="turnToGoodsList">取消</el-button>
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </div>
      </div>
      <!-- 图文信息 -->
      <component
        v-if="activeStep == 1"
        :is="'goodsMediaInfo'"
        :goods-info="formData"
        @prev="prevStep"
        @save="saveGoodsBaseInfo"/>
    </basic-container>
  </div>
</template>

<script>
  import goodsModelSelecter from './component/goodsModelSelecter'
  import selImgPhotogallery from '@/components/pds/common/sel_img_photogallery'
  import Request from '../../crm/goods/request'
  import {getSliderImage, uploadSliderImages} from '@/api/goods/goods'
  import goodsMediaInfo from '../../crm/goods/addGoods/components/goodsMediaInfo'
  import { goodsOption } from '../../const/crud/supply/addsupplygoods'
  import {addGoods} from '../../api/supply/suppliergoods'
  import {getCategoryTree} from "../../api/goods/goodscategory"
  export default {
    components: {
      goodsModelSelecter,
      selImgPhotogallery,
      goodsMediaInfo
    },
    data() {
      return {
        formData: {
          shopId: '',
          goodsCategoryId: '',
          //排序值
          sort: '100',
          //商品名称
          goodsName: '',
          categoryName: '',
          //计量单位
          unit: '',
          // 图片地址
          thumbUrl: '',
          //轮播图
          photoList: [],
          //市场价
          marketPrice: '',
          // 库存数量
          storage: '1000',
          // 搜索关键词
          simpleDesc: '',
          // 商品描述
          detailDesc: '',
          // 商品状态
          goodsStatus: '0',
          //会员价
          vipPrice: '',
          //销售规则
          saleRule: '',
          //虚拟价格
          virtualPrice: '',
          //  是否c端销售
          salecFlag: '0',
          // 商品类型
          goodsType: '0',
          // 商品来源
          goodsFrom: '',
          // 赠品标记
          goodsGift: '',
          //  配送规则标记
          deliveryRule: '',
          //  服务选项标记
          serviceSelection: '',
          // 扫码购编码
          scanCode: '',
        },
        request: new Request(),
        activeStep: 0,
        option: goodsOption,
        goodsCateLoading: false,
        // 分类选择框
        showCategoryTree: false,
        // 商品分类列表
        goodsCategory: [],
        defaultProps: {
          defaultExpandAll: true,
          label: 'name',
          value: 'id',
          children: 'children'
        },
        categoryTreeProps: {
          children: 'children',
          label: 'name'
        },
        // 图片上传
        picturePreviewVisible: false,
        pictureList: [],
        sleImg: false,
        sleImgType: 1,
        // delImages: [],
        updImages: [],
        // 规格
        hasModel: true,
        shopId: ''
      }
    },
    beforeRouteEnter(to, from, next) {
      next(vm => {
        vm.shopId = vm.$route.query.res.shopId;
        vm.getGoodsCategory()
      });
    },
    methods: {
      // 获取分类
      getModelInfo(val) {
        console.log(val);
      },
      async getGoodsCategory() {
        this.goodsCateLoading = true
        this.showCategoryTree = true
        const params = {
          shopId: this.shopId
        }
        getCategoryTree(params).then(res => {
          console.log(res);
          const data = res.data.data
          this.goodsCateLoading = false
          this.goodsCategory = data
        })
      },
      // 分类选择节点
      checkGoodsCategory(node, nodes) {
        // console.log(node)
        this.formData.goodsCategoryId = node.id
        if (nodes.checkedKeys.length > 0) {
          this.$refs.categoryTree.setCheckedKeys([node.id])
        }
        if (node.children && node.children.length > 0) {
          this.$refs.categoryTree.setChecked(node, false, false)
          this.$message.warning('父节点不可选')
        }
        if (this.formData.categoryName) {
          this.formData.categoryName = node.name
        } else {
          this.$set(this.formData, 'categoryName', node.name)
        }
        if (this.formData.categoryId) {
          this.formData.categoryId = node.id
        } else {
          this.$set(this.formData, 'categoryId', node.id)
        }
      },
      //分类选择节点
      handleChange(val) {
        console.log(val);
      },
      // 选择图片
      sel_img(type) {
        if(type == 1) {
          this.sleImg = true
          this.sleImgType = type
        }
        if (this.formData.photoList.length == 5) {
          this.$message.error("轮播最多选择5张")
        } else {
          this.sleImg = true
          this.sleImgType = type
        }
      },
      onSelectImgs(imgs) {
        console.log(imgs);
        if (this.sleImgType == 1) {
          this.formData.thumbUrl = imgs[0].picUrl
          this.sleImg = false
        }
        if (this.sleImgType == 2) {
          let len = imgs.length + this.formData.photoList.length
          const currlen = this.formData.photoList.length
          if (len > 5) {
            // this.$message.error("轮播最多选择5张")
            for(let i=0;i< 5 - currlen;i++) {
              const photoItem = {id: imgs[i].id, picUrl: imgs[i].picUrl}
              this.formData.photoList.push(photoItem)
              this.sleImg = false
            }
          } else {
            imgs.forEach( item => {
              const photoItem = {id: item.id, picUrl: item.picUrl}
              this.formData.photoList.push(photoItem)
              console.log(this.formData);
            })
            this.sleImg = false
          }
        }
      },
      // 删除商品主图
      handlePictureRemove() {
        this.formData.thumbUrl = ''
      },
      // 查看商品主图
      handlePicturePreview() {
        this.picturePreviewVisible = true
      }, // 删除el-upload的图片
      sliderPictureRemove(index) {
        // this.delImages.push(this.sliderImage[index].url)
        this.formData.photoList.splice(index, 1)
      },
      // 取消
      turnToGoodsList() {
        this.goBack()
      },
      //返回
      goBack(time = 1000) {
        let that = this;
        setTimeout(function () {
          that.$store.commit('DEL_ONE_TAG', that.$route);
          that.$router.go(-1);
        }, time);
      },
      // 下一步
      nextStep() {
        if (this.formData.goodsName &&
          this.formData.unit &&
          this.formData.goodsCategoryId &&
          this.formData.thumbUrl &&
          this.formData.marketPrice &&
          this.formData.storage &&
          this.$refs.goodsModelsComponent.tableData.length != 0
        ) {
          // this.syncModelInfo()
          this.activeStep = 1
        } else {
          if(!this.formData.goodsCategoryId) {
            this.$message.error('请选择分类!')
          }
          else if(!this.formData.thumbUrl) {
            this.$message.error('请选择商品主图!')
          }
          else if(this.$refs.goodsModelsComponent.tableData.length == 0) {
            this.$message.error('请填写商品规格')
          }
          else{
            this.$message.error('有必填项未填写!')
          }
        }
      },
      syncModelInfo() {
        const ref = this.$refs.goodsModelsComponent
        if (ref) {
          let modelList = ref.tableData
          console.log(modelList);
          let typeName = ref.checkedModels.join()
          modelList.forEach(item => {
            let modelName = item.modelName.join()
            item.modelName = modelName
            item.typeName = typeName
          })
          this.formData.modelList = modelList
          console.log(this.formData);
        }
      },
      // 保存上架
      saveGoodsBaseInfo() {
        this.formData.shopId = this.shopId
        this.syncModelInfo()
        console.log(this.formData);
        addGoods(this.formData).then(res => {
          this.$message.success('保存成功')
          this.goBack()
        })
      },
      // 上一步
      prevStep(step) {
        this.activeStep = step
      }


    }
  }
</script>

<style lang="scss" scoped>
  .progress {
    padding-top: 10px;
    width: 50%;
    margin-top: 10px;
    margin-right: 0;
    margin-left: 0;
    margin: auto
  }

  .goods-category {
    border: 1px solid #e9e9e9;
    margin: 10px 0 0 10px;
    width: 286px;
    border-radius: 3px;
    max-height: 300px;
    overflow: scroll;
  }

  .thumbUrl {
    position: relative;
    width: 150px;
    height: 150px;
    float: left;
    margin-left: 15px;
    margin-bottom: 15px;
    line-height: 146px;
    overflow: hidden;
    border-radius: 6px;

    .hover_show {
      position: absolute;
      top: 0;
      left: 0;
      background-color: rgba(0, 0, 0, 0.5);
      width: 100%;
      height: 100%;
      display: none;
      padding-left: 40px;

      i {
        color: #fff;
        margin: 0 10px;
        cursor: pointer;
      }
    }

    img {
      width: 100%;
      height: 100%;
    }
  }

  .thumbUrl:hover .hover_show {
    display: block;
  }

  .select_img {
    float: left;
    margin-left: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 148px;
    height: 148px;
    border: 1px dashed #c0ccda;
    background-color: #fbfdff;
    font-size: 28px;
    color: #8c939d;
    cursor: pointer;
    border-radius: 6px;
  }

  .goods-models-wrap {
    margin: 0 0 50px 40px;
  }

  .button-group__center {
    display: flex;
    justify-content: center;
  }

  .tbngroup {
    position: absolute;
    bottom: 50px;
    left: 50%;
  }
</style>
